package com.handong.handserialprogram.module.singletask;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.ColorContant;
import com.handong.handserialprogram.constants.KeyConstant;
import com.handong.handserialprogram.model.entities.CriminalEntity;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.base.EmergencyActivity;
import com.handong.handserialprogram.module.routemap.RouteMapActivity;
import com.handong.handserialprogram.module.voice.VoiceActivity;
import com.handong.handserialprogram.service.LocateService;
import com.handong.handserialprogram.service.SignalRService;
import com.handong.handserialprogram.utils.AppCache;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.CallBackUtil;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.UserGuideUtil;
import com.handong.handserialprogram.utils.ViewUtil;
import com.handong.handserialprogram.voice.VoiceImpl;
import com.handong.handserialprogram.widget.guideview.Guide;
import com.handong.handserialprogram.widget.guideview.GuideBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
  import static com.handong.handserialprogram.utils.AppCache.getContext;


/**
 * 任务详情列表
 */
public class  MissionActivity extends EmergencyActivity<MissionPresenter> implements BaseView {

    private static final String TAG = MissionActivity.class.getSimpleName();
    private LinearLayout mProgressBarLayout;
    private RelativeLayout mContentLayout;
    private RecyclerView mPersonList;
    private TextView mStartMission,mResume;
    private TextureView surfaceView;

    private CriminalListAdapter mListAdapter;
    public String mMissionID = null;
    public int mMissionStatus;
    protected boolean isForceFinish=false;

    private LocateService mLocateService;
    private String mTaskName;
    private String mTaskCar;
    private String mTaskTime;
    private MaterialDialog mMissionInfoDialog;
    //    private ImageView mBg;
//    private TextView mUpload;
//    private TextView mStop;
//    private TextView mTime;
    private List<CriminalEntity> mCriminalEntityList;
    private ImageView mMenu,mMenuOpen,mVoice,mMap,mChatInfo1,mChatInfo2;
    private boolean isPause=false;
    private boolean isRejoin=false;


    public static final int REQUEST_MEDIA_PROJECTION = 1002;
    public static final int REQUEST_CAMERA_PERMISSION = 1003;
    public static final int REQUEST_STORAGE_PERMISSION = 1004;

    // 默认分辨率
    int width = 1280, height = 720;



    List<String> listResolution = new ArrayList<>();

    //MediaStream mMediaStream;

    static Intent mResultIntent;
    static int mResultCode;
    //private UpdateMgr update;

    private ServiceConnection conn;
    private ServiceConnection mConnection;
    private boolean isReceiveChat=false;

    //private boolean mNeedGrantedPermission;

    private static final String STATE = "state";
    private static final int MSG_STATE = 1;
    private VoiceImpl mVoiceImpl;

    private long mExitTime;//声明一个long类型变量：用于存放上一点击“返回键”的时刻


    @Override
    protected int getContentViewID() {
        return R.layout.activity_mission;
    }

    @Override
    protected MissionPresenter createPresenter() {
        return new MissionPresenter(this);
    }

    @Override
    protected void initViewByID() {
        final Context context=this;

        mProgressBarLayout = (LinearLayout) findViewById(R.id.progressBarLayout);
        mContentLayout = (RelativeLayout) findViewById(R.id.missionContentLayout);
        mPersonList = (RecyclerView) findViewById(R.id.missionPersonList);
        mStartMission = (TextView) findViewById(R.id.missionStartText);
        mResume=(TextView) findViewById(R.id.missionResumeOrPause) ;
        mChatInfo1=(ImageView)findViewById(R.id.iv_chatInfo1);
        mChatInfo2=(ImageView)findViewById(R.id.iv_chatInfo2);
//        mBg=(ImageView)findViewById(R.id.bg);
//        mUpload=(TextView)findViewById(R.id.upload) ;
//        mStop=(TextView)findViewById(R.id.stop);
//        mTime=(TextView)findViewById(R.id.time);
        mStartMission.setOnClickListener(this);
        findView(R.id.headerOptionLayout).setOnClickListener(this);
        mMenu=(ImageView)findViewById(R.id.menu);
        mMenuOpen=(ImageView)findViewById(R.id.menuopen);
        mVoice=(ImageView)findViewById(R.id.voice);
        mMap=(ImageView)findViewById(R.id.map);
        mMap.setOnClickListener(this);
        mMenu.setOnClickListener(this);
        mMenuOpen.setOnClickListener(this);
        mVoice.setOnClickListener(this);
        mResume.setOnClickListener(this);

        Intent intent = new Intent();
        intent.setClass(this, SignalRService.class);
        startService(intent);
        mConnection = new ServiceConnection()
        {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service)
            {
                // We've bound to SignalRService, cast the IBinder and get SignalRService instance
                SignalRService.LocalBinder binder = (SignalRService.LocalBinder) service;
                sService = binder.getService();
                sService.IsRunning=true;
                sService.startSignalR(context);
                mBound = true;

                AppCache.setSignalRService(sService);
                sService.setOnReconnectingListener(new CallBackUtil.OnReconnectingListener(){

                    @Override
                    public void onReconnecting() {
                        sService.joinRoom(mMissionID,SPUtil.getStringValue(SPUtil.USER_NAME));
                        sService.Subscribe();

                    }
                });
                sService.setOnReceiveListener(new CallBackUtil.OnReceiveListener() {
                    @Override
                    public void onReceive(String companyCode,String room, String message) {
                        if (!TextUtils.isEmpty(message)) {

                            try {
                                JSONObject obj = new JSONObject(message);

                                if (!obj.getString("username").equals(SPUtil.getStringValue(SPUtil.USER_NAME))) {
                                    receiveMessageVoice();
                                    isReceiveChat=true;
                                    mChatInfo1.setVisibility(View.VISIBLE);
                                    if (mMenuOpen.getVisibility()==View.VISIBLE)
                                    {
                                        mChatInfo2.setVisibility(View.VISIBLE);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                showShortToast("服务器无响应");
                            }

                        }
                    }
                });

            }
            @Override
            public void onServiceDisconnected(ComponentName arg0)
            {
                mBound = false;
            }
        };
        bindService(intent, mConnection, Context.BIND_ADJUST_WITH_ACTIVITY);
//mPresenter.updateDelay(100);
//        HubConnection hubConnection = HubConnectionBuilder.create(serverUrl).build();
//        //IHubProxy HubProxy== hubConnection..CreateHubProxy("ServerHub");
//        hubConnection.start().blockingAwait();
//        hubConnection.send("sendWinform", "测试");
//        sService(mMissionID,SPUtil.getStringValue(SPUtil.USER_NAME));

    }

    protected void receiveMessageVoice()
    {
        if (mVoiceImpl == null) {
            mVoiceImpl = VoiceImpl.getInstance(this);
        }
        mVoiceImpl.addSound(R.raw.info_new_message);
        mVoiceImpl.playVoice();
    }

    private SignalRService sService;
    private boolean mBound = false;


    @Override
    protected void initViewDataRes() {
        initHeaderLayout(false);
        //setOptionOnClick();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mMissionID = bundle.getString(KeyConstant.MISSION_ID);

            mTaskName = bundle.getString(KeyConstant.MISSION_NAME);
            mTaskCar = bundle.getString(KeyConstant.MISSION_CAR);
            mTaskTime = bundle.getString(KeyConstant.MISSION_TIME);
            if (bundle.getBoolean(KeyConstant.IS_REJOIN))
            {
                isRejoin=true;
            }

        }

        //默认打开报警
        SPUtil.putBooleanValue(SPUtil.RING_STATUS, true);


        ViewUtil.closeDefaultAnimator(mPersonList);
        mPresenter.requestMissionDetail(mMissionID);
        //ViewUtil.changeBtnStatus(mStartMission, ColorContant.MISSION_WAITING, R.string.open_upload_data);

        /**
         * 启动定位SDK并传给串口
         */
        Intent intent = new Intent(this, LocateService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

        File youyuan = getFileStreamPath("SIMYOU.ttf");
        if (!youyuan.exists()) {
            AssetManager am = getAssets();

            try {
                InputStream is = am.open("zk/SIMYOU.ttf");
                FileOutputStream os = openFileOutput("SIMYOU.ttf", MODE_PRIVATE);
                byte[] buffer = new byte[1024];
                int len;

                while ((len = is.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }

                os.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.headerBackLayout:
                finish();
                break;
            case R.id.headerOptionLayout://显示任务信息
                showTaskInfo();
                break;
            case R.id.map://地图显示
                Bundle intent = new Bundle();
                intent.putString("route", mPresenter.routeList);
                intent.putString("polygon", mPresenter.polygonList);
                intent.putString("origin", mPresenter.startMarkerPoint);
                intent.putString("destination", mPresenter.endMarkerPoint);
                openActivity(RouteMapActivity.class,intent);
                overridePendingTransition(R.anim.slide_bottom_in, R.anim.anim_no);
                break;
            case R.id.missionStartText://开始上传数据
                dealStartClick(mMissionStatus);
                break;
            case R.id.menu:
//                Vibrator vibrator=(Vibrator)getSystemService(Service.VIBRATOR_SERVICE);
//                vibrator.vibrate(new long[]{0,1000}, -1);
                mMenuOpen.setVisibility(View.VISIBLE);
                mMap.setVisibility(View.VISIBLE);
                mVoice.setVisibility(View.VISIBLE);
                mMenu.setVisibility(View.GONE);
                if (isReceiveChat){
                    mChatInfo2.setVisibility(View.VISIBLE);
                }
                else{
                    mChatInfo2.setVisibility(View.GONE);
                }
                break;
            case R.id.menuopen:
                mMenuOpen.setVisibility(View.GONE);
                mMap.setVisibility(View.GONE);
                mVoice.setVisibility(View.GONE);
                mMenu.setVisibility(View.VISIBLE);
                mChatInfo2.setVisibility(View.GONE);
                break;
            case R.id.voice:
                isReceiveChat=false;
                mChatInfo1.setVisibility(View.GONE);
                mChatInfo2.setVisibility(View.GONE);
                Bundle bundle = new Bundle();
                bundle.putString(KeyConstant.MISSION_ID, mMissionID);
                openActivityForReuslt(VoiceActivity.class, bundle,322);
                break;
            case R.id.missionResumeOrPause:

                updateMissionState();


                break;
        }
        super.onClick(v);
    }

    protected void updateMissionState()
    {
        if (isPause)
        {
            state=2;
            mPresenter.queryMissionResumeState(mMissionID);
            //showResumeDialog();
//                    mPresenter.resumeUploadData();
//                    isPause=false;
        }
        else{
            if (mPresenter.checkIsAnyCriminalEscape())
            {
                //有逃脱罪犯，提示并返回，不允许结束任务
                AppUtil.showShortToast(this, "当前有设备为非正常状态或距离超过"+SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)+"米，不允许暂停任务！");
                return;
            }
            state=1;
            showPauseDialog();
//                    mPresenter.pauseUploadData();
//                    isPause=true;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        FootRingNewEntity entity = null;
        if (data != null && (entity = data.getExtras().getParcelable(KeyConstant.SINGLE_PERSON)) != null) {
            mListAdapter.addFootRing(entity);
            //mPresenter.init();
        } else {
            mListAdapter.resetIndex();
            //mPresenter.setIndex(-1);
        }
        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            if (resultCode == RESULT_OK) {
                Log.d(TAG, "get capture permission success!");

                mResultCode = resultCode;
                mResultIntent = data;
            }
        }

        if (requestCode==322)
        {
            if (resultCode==RESULT_OK){
                if (sService!=null) {
                    sService.setOnReconnectingListener(new CallBackUtil.OnReconnectingListener() {

                        @Override
                        public void onReconnecting() {
                            sService.joinRoom(mMissionID, SPUtil.getStringValue(SPUtil.USER_NAME));
                            sService.Subscribe();
                        }
                    });
                    sService.setOnReceiveListener(new CallBackUtil.OnReceiveListener() {
                        @Override
                        public void onReceive(String companyCode, String room, String message) {
                            if (!TextUtils.isEmpty(message)) {

                                try {
                                    JSONObject obj = new JSONObject(message);

                                    if (!obj.getString("username").equals(SPUtil.getStringValue(SPUtil.USER_NAME))) {
                                        receiveMessageVoice();
                                        isReceiveChat = true;
                                        mChatInfo1.setVisibility(View.VISIBLE);
                                        if (mMenuOpen.getVisibility() == View.VISIBLE) {
                                            mChatInfo2.setVisibility(View.VISIBLE);
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    showShortToast("服务器无响应");
                                }

                            }
                        }
                    });
                }
            }
        }
    }

    /**
     * 显示犯人列表
     * @param list
     */
    protected void showCriminalList(List<CriminalEntity> list) {
        LinearLayout parent = (LinearLayout) mProgressBarLayout.getParent();
        parent.removeViewAt(1);
        mProgressBarLayout = null;
        if (mListAdapter == null) {
            mCriminalEntityList=list;
            mListAdapter = new CriminalListAdapter(mCriminalEntityList, this);
            mPersonList.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
            mPersonList.setAdapter(mListAdapter);
        }
        dismissLoadingDialog();
        mContentLayout.setVisibility(View.VISIBLE);
    }

    /**
     * 加载失败
     * @param isLoadFail
     */
    protected void loadMissionInfoFail(boolean isLoadFail) {
        View view = mProgressBarLayout.getChildAt(0);
        if (view instanceof ImageView) {
            dismissLoadingDialog();
            return;
        }
        LinearLayout parent = (LinearLayout) mProgressBarLayout.getParent();
        parent.removeViewAt(1);
        final Context context=this;
        if (isLoadFail) {
            mProgressBarLayout = ViewUtil.showTipLayout(context, R.drawable.load_tip_error,
                    R.string.tip_load_data_error, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (AsyncHttpUtil.isNetworkConnected(context)) {
                                showLoadDialog("重新加载人员信息...");
                                mPresenter.requestMissionDetail(mMissionID);
                            }
                        }
                    });
        } else {
            mProgressBarLayout = ViewUtil.showTipLayout(context, R.drawable.load_tip_no_mission,
                    R.string.tip_mission_no_criminal, null);
        }
        parent.addView(mProgressBarLayout, 1);
    }

    /**
     * 处理上传数据
     * @param status
     */
    public void dealStartClick(int status) {
        switch (status) {
            case KeyConstant.MISSION_WAITING://等待
                final Context context=this;
                // todo 改为一对一
//                if (!mPresenter.isBandingRings()) {
//                    showGuideView(mListAdapter.getFirstView(), R.id.btnPersonSetRing);
//                    return;
//                }
                // todo 一对多打开
//                if(mPresenter.isNoBandingRings()){
//                    AppUtil.showLengthToast(this,"请至少为一个犯人设置脚环");
//                    return;
//                }
//               else



//                   if(mPresenter.hasNotBandingRings()){
////                    AppUtil.showLengthToast(this,"请为所有犯人设置脚环");
////                    return;
//                   MaterialDialog dialog = new MaterialDialog.Builder(this)
//                           .title(R.string.dialog_title_careful)
//                           .content("有犯人未设置脚环,是否继续？")
//                           .canceledOnTouchOutside(false)
//                           .positiveText("继续开始")
//                           .positiveColorRes(R.color.back_ground_green)
//                           .onPositive(new MaterialDialog.SingleButtonCallback() {
//                               @Override
//                               public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                                   if (!isRejoin)
//                                   {
//                                       mPresenter.requestStartMission(mMissionID);
//                                   }
//                                   mPresenter.open2Server(mMissionID);//上传数据
//                                   mMissionStatus = KeyConstant.MISSION_WORKING;
//                                   mMenu.setVisibility(View.VISIBLE);
//                                   mStartMission.setText(R.string.close_upload_data);
//                                   mResume.setVisibility(View.VISIBLE);
//                                   FrameLayout.LayoutParams frameParams =(FrameLayout.LayoutParams) mStartMission.getLayoutParams();
//                                   frameParams.width = AppUtil.dip2px(context,207);
//                                   mStartMission.setLayoutParams(frameParams);
//                                   //ViewUtil.changeBtnStatus(mStartMission, ColorContant.MISSION_NORMAL, R.string.close_upload_data);
//                               }
//                           })
//                           .negativeColorRes(R.color.dialog_bg)
//                           .negativeText(R.string.dialog_negative_text)
//                           .build();
//                   ViewUtil.removeHomeKeyListener(dialog);
//                }
//                else{

                if (!isRejoin)
                {
                    mPresenter.requestStartMission(mMissionID);
                }
                mPresenter.open2Server(mMissionID);//上传数据
                mMissionStatus = KeyConstant.MISSION_WORKING;
                mMenu.setVisibility(View.VISIBLE);
                mStartMission.setText(R.string.close_upload_data);
                mResume.setVisibility(View.VISIBLE);
//                LinearLayout.LayoutParams frameParams =(LinearLayout.LayoutParams) mStartMission.getLayoutParams();
//                frameParams.width = AppUtil.dip2px(this,207);
//                mStartMission.setLayoutParams(frameParams);
                //ViewUtil.changeBtnStatus(mStartMission, ColorContant.MISSION_DOING, R.string.close_upload_data);
                // }



                break;
            case KeyConstant.MISSION_WORKING://进行中
                if (mPresenter.checkIsAnyCriminalEscape())
                {
                    //有逃脱罪犯，提示并返回，不允许结束任务
                    AppUtil.showShortToast(this, "当前有设备为非正常状态或距离超过"+SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)+"米，不允许结束任务！");
                    return;
                }
                state=0;
//                mPresenter.finishMiss2Server();
//                mPresenter.stopMission();
                showFinishDialog();
                break;
            case KeyConstant.MISSION_FINISH://任务完成
                mPresenter.finishMiss2Server();
                mPresenter.stopMission();
                break;

        }
    }

    /**
     * 更新距离
     */
    protected void refreshRingDistance(int index){
        mListAdapter.notifyItemChanged(index);
    }

    /**
     * 设置任务状态为进行中
     */
    protected boolean isMissionExecuting(){
        return mMissionStatus == KeyConstant.MISSION_WORKING;
    }

    /**
     * 是否绑定脚环
     */
   /* protected boolean isBindRing(){
        return mPresenter.isBandingRing();
    }*/

    private int state=0;

    /**
     * 请求结束上传数据
     */
    private void showFinishDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_careful)
                .content("是否向指挥中心请求结束任务？")
                .canceledOnTouchOutside(false)
                .positiveText(R.string.dialog_positive_text)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        showPasswordDialog();
                    }
                })
                .negativeColorRes(R.color.dialog_bg)
                .negativeText(R.string.dialog_negative_text)
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     * 身份验证
     */
    private void showPasswordDialog() {
        final Context context=this;
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title("身份验证")
                .inputType(InputType.TYPE_TEXT_VARIATION_PASSWORD)
                .input("请输入管理员密码以验证身份", null, new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {

                    }
                })
                .canceledOnTouchOutside(false)
                .positiveText(R.string.dialog_positive_text)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        String password=dialog.getInputEditText().getText().toString();
                        if(mPresenter.checkPassword(password))
                            if(state==0){
                                mPresenter.queryMissionState(mMissionID);
                            }
                            else if(state==1){
                                mPresenter.queryMissionPauseState(mMissionID);
                            }
                            else{

                            }

                        else {
                            AppUtil.showShortToast(context, "密码错误！");
                            dialog.dismiss();
                        }
                    }
                })
                .negativeColorRes(R.color.dialog_bg)
                .negativeText(R.string.dialog_negative_text)
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     * 请求暂停上传数据
     */
    private void showPauseDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_careful)
                .content("是否向指挥中心请求暂停任务？")
                .canceledOnTouchOutside(false)
                .positiveText(R.string.dialog_positive_text)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        showPasswordDialog();
                    }
                })
                .negativeColorRes(R.color.dialog_bg)
                .negativeText(R.string.dialog_negative_text)
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     * 请求恢复上传数据
     */
    private void showResumeDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_careful)
                .content("是否向指挥中心请求恢复任务？")
                .canceledOnTouchOutside(false)
                .positiveText(R.string.dialog_positive_text)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        showPasswordDialog();
                    }
                })
                .negativeColorRes(R.color.dialog_bg)
                .negativeText(R.string.dialog_negative_text)
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    protected void changePause2Resume()
    {
        if (isPause){
            mResume.setText("暂停任务");
            mPresenter.setIsUploadPause(!isPause);
            isPause=false;
        }
        else{
            mResume.setText("恢复任务");
            mPresenter.setIsUploadPause(!isPause);
            isPause=true;
        }
    }

    /**
     * 休眠脚环成功
     */
    protected void stopMissionSuccess() {
        showLoadDialog("正在休眠脚环...");
        mMissionStatus = KeyConstant.MISSION_FINISH;
        ViewUtil.changeBtnStatus(mStartMission, ColorContant.MISSION_NORMAL, R.string.stopped_upload_data);
    }



    /**
     *  服务器结束任务成功
     */
    public void showResponseSuccessDialog() {
        if (state==0)
        {
            final Context context =this;
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title(R.string.dialog_title_request_success)
                    .content("指挥中心已同意结束任务，是否结束任务并注销脚环(注销时请确保当前所有设备为正常状态且距离为"+SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)+"米以内)?")
                    .positiveColorRes(R.color.back_ground_green)
                    .canceledOnTouchOutside(false)
                    .positiveText("立即结束")
                    .negativeColorRes(R.color.dialog_bg)
//                    .negativeText("直接退出")
                    .autoDismiss(false)
//                    .onNegative(new MaterialDialog.SingleButtonCallback() {
//                        public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
//                            logoutFootRingWarning();
//                        }
//                    })
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            if (mPresenter.checkIsAnyCriminalEscape())
                            {
                                //dialog.setContent("当前有设备为非正常状态或距离超过"+SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)+"米，不允许结束任务！");
                                AppUtil.showShortToast(context, "当前有设备为非正常状态或距离超过"+SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)+"米，不允许结束任务！");
                                logoutFootRingWarning();
                            }
                            else{
                                dialog.dismiss();
                                mPresenter.stopMission();
                            }

                        }
                    })
                    .build();
            ViewUtil.removeAllKeyListener(dialog);
        }
        else if(state==1){
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title(R.string.dialog_title_request_success)
                    .content("指挥中心已同意暂停任务！")
                    .positiveColorRes(R.color.back_ground_green)
                    .canceledOnTouchOutside(false)
                    .positiveText(R.string.dialog_positive_text)
                    .build();
            ViewUtil.removeAllKeyListener(dialog);
            changePause2Resume();
        }
        else{
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title(R.string.dialog_title_request_success)
                    .content("指挥中心已同意恢复任务！")
                    .positiveColorRes(R.color.back_ground_green)
                    .canceledOnTouchOutside(false)
                    .positiveText(R.string.dialog_positive_text)

                    .build();
            ViewUtil.removeAllKeyListener(dialog);
            changePause2Resume();
        }
    }

    /**
     * 服务器请求结束任务
     */
    public void showMissionOverDialog() {
        Intent intent = new Intent(this, MissionActivity.class);
        startActivity(intent);
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_careful)
                .content("指挥中心发出结束任务命令，是否立即执行并注销脚环(注销时请确保当前所有设备为正常状态且距离为"+SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)+"米以内)?")
                .positiveColorRes(R.color.back_ground_green)
                .canceledOnTouchOutside(false)
                .positiveText(R.string.dialog_positive_now_execute)
                .negativeColorRes(R.color.dialog_bg)
                .negativeText("直接退出")
                .autoDismiss(false)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        logoutFootRingWarning();

                    }
                })
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (mPresenter.checkIsAnyCriminalEscape())
                        {
                            AppUtil.showShortToast(context, "当前有设备为非正常状态或距离超过"+SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)+"米，不允许结束任务！");
                        }
                        else{
                            dialog.dismiss();
                            mPresenter.stopMission();
                        }
                    }
                })
                .build();
        ViewUtil.removeAllKeyListener(dialog);
    }

    /**
     * 服务器任务结束连接超时
     */
    public void showFinMissTimeOutDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_request_fail)
                .content("指挥中心无回复，请通过其他方式联系！")
                .canceledOnTouchOutside(false)
                .positiveColorRes(R.color.back_ground_green)
                .positiveText(R.string.dialog_positive_text)
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }
    /**
     * 服务器不允许结束任务
     */
    public void showServerRejectDialog() {
        if(state==0)
        {
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title(R.string.dialog_title_request_reject)
                    .content("指挥中心不允许结束任务，请继续执行！")
                    .positiveColorRes(R.color.back_ground_green)
                    .canceledOnTouchOutside(false)
                    .positiveText(R.string.dialog_positive_text)
                    .build();
            ViewUtil.removeHomeKeyListener(dialog);
        }
        else if(state==1)
        {
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title(R.string.dialog_title_request_reject)
                    .content("指挥中心不允许暂停任务，请继续执行！")
                    .positiveColorRes(R.color.back_ground_green)
                    .canceledOnTouchOutside(false)
                    .positiveText(R.string.dialog_positive_text)
                    .build();
            ViewUtil.removeHomeKeyListener(dialog);
        }
        else if(state==2)
        {
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title(R.string.dialog_title_request_reject)
                    .content("指挥中心不允许恢复任务！")
                    .positiveColorRes(R.color.back_ground_green)
                    .canceledOnTouchOutside(false)
                    .positiveText(R.string.dialog_positive_text)
                    .build();
            ViewUtil.removeHomeKeyListener(dialog);
        }

    }

    /**
     * 请求结束任务错误
     */
    public void showSendErrorDialog() {
        if(state==0)
        {
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title(R.string.dialog_title_request_fail)
                    .content("无法发出结束请求，请检查本机网络！")
                    .positiveColorRes(R.color.back_ground_green)
                    .canceledOnTouchOutside(false)
                    .positiveText(R.string.dialog_positive_text)
                    .build();
            ViewUtil.removeHomeKeyListener(dialog);
        }
        else if(state==1)
        {
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title(R.string.dialog_title_request_fail)
                    .content("无法发出暂停请求，请检查本机网络！")
                    .positiveColorRes(R.color.back_ground_green)
                    .canceledOnTouchOutside(false)
                    .positiveText(R.string.dialog_positive_text)
                    .build();
            ViewUtil.removeHomeKeyListener(dialog);
        }
        else{
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .title(R.string.dialog_title_request_fail)
                    .content("无法发出恢复请求，请检查本机网络！")
                    .positiveColorRes(R.color.back_ground_green)
                    .canceledOnTouchOutside(false)
                    .positiveText(R.string.dialog_positive_text)
                    .build();
            ViewUtil.removeHomeKeyListener(dialog);
        }
    }

    private Guide mGuideInstance;

    /**
     * 设置蒙版
     */
    public void showGuideView(View view, int res) {
        if (mGuideInstance != null) {
            return;
        }
        mGuideInstance = UserGuideUtil.showBindRingGuideView(view, res, this, new GuideBuilder.OnVisibilityChangedListener() {
            @Override
            public void onShown() {
            }

            @Override
            public void onDismiss() {
                mGuideInstance = null;
            }
        });
    }

    @Override
    public void openActWithAnim(Class<? extends FragmentActivity> cls, Bundle attr, int index, int requestCode) {
        if (attr != null){
            attr.putString(KeyConstant.MISSION_ID, mMissionID);
        }
        // mPresenter.setIndex(index);//第几个跳转
        super.openActWithAnim(cls, attr, index, requestCode);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode && mGuideInstance != null
                && mGuideInstance.onKey(null, keyCode, event)) {
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 显示任务信息
     */
    private void showTaskInfo() {
        if (mMissionInfoDialog == null) {
            View customView = LayoutInflater.from(this).inflate(R.layout.dialog_single_task_info, null, false);
            TextView reason = (TextView) customView.findViewById(R.id.taskInfoReason);
            TextView startPlace = (TextView) customView.findViewById(R.id.taskInfoStartPlace);
            TextView devices = (TextView) customView.findViewById(R.id.taskInfoDevices);
            //TextView hospital = (TextView) customView.findViewById(R.id.taskInfoHospital);
            TextView executeCar = (TextView) customView.findViewById(R.id.taskInfoExecuteCar);
            //TextView otherPerson = (TextView) customView.findViewById(R.id.taskInfoDoctor);
            //TextView moreInfo = (TextView) customView.findViewById(R.id.taskInfoMore);
            reason.setText(mTaskName);
            devices.setText(SPUtil.getStringValue(SPUtil.PHONE_NAME));
            //hospital.setText(mEntity.getTaskEndPlace());
            startPlace.setText(mTaskTime);
            if (!TextUtils.isEmpty(mTaskCar)) {
                executeCar.setText(mTaskCar);
            } else {
                executeCar.setText("暂无");
            }
            mMissionInfoDialog = new MaterialDialog.Builder(this)
                    .title("任务详情")
                    .customView(customView, true)
                    .positiveText("了解")
                    .positiveColorRes(R.color.btn_green_bg)
                    .build();
        }
        ViewUtil.removeHomeKeyListener(mMissionInfoDialog);
    }

    /**
     * 退出
     */
    public void showExitDialog() {
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                .content("请休眠脚环后，再退出？")
                .negativeColorRes(R.color.dialog_bg)
                .positiveText(R.string.dialog_positive_sleep)
                .positiveColorRes(R.color.back_ground_green)
                .negativeText(R.string.dialog_negative_text)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.logoutAllFootRing();

                    }
                }).build());
    }

    /**
     * 关闭脚环
     */
    protected void finishRefreshDistance() {
        mMissionStatus = KeyConstant.MISSION_FINISH;
        if (mListAdapter != null) {
            mListAdapter.notifyDataSetChanged();
        }
        //isForceFinish=true;
        finish();
    }

    /**
     * 休眠脚环失败
     */
    protected void logoutFootRingError(final String id) {
        mPresenter.resumeCurrentFootRing();
        final MaterialDialog dialog = new MaterialDialog.Builder(this)
                .content("休眠脚环失败，请确保当前所有设备为正常状态且距离为"+SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)+"米以内，并重试！")
                .negativeColorRes(R.color.dialog_bg)
                .negativeText("直接退出")
                .positiveText(R.string.dialog_positive_again)
                .autoDismiss(false)
                .positiveColorRes(R.color.back_ground_green)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        logoutFootRingWarning();

                    }
                })
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        if (mPresenter.checkIsAnyCriminalEscape())
                        {
                            AppUtil.showShortToast(context, "当前有设备为非正常状态或距离超过"+SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)+"米，不允许结束任务！");
                        }
                        else{
                            paramAnonymousMaterialDialog.dismiss();
                            mPresenter.logoutAllFootRing();
                        }

                    }
                }).build();
        //if (dialog)
        if(dialog.isCancelled()) {
            ViewUtil.removeHomeKeyListener(dialog);
        }
    }

    /**
     * 注销脚环失败后警告立即结束后的后果
     */
    protected void logoutFootRingWarning()
    {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title("警告")
                .content("若直接退出会引起脚环逃脱报警，是否确认直接退出(重试时请确保当前所有设备为正常状态且距离为"+SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)+"米以内)！")
                .negativeColorRes(R.color.dialog_bg)
                .negativeText("确认直接退出")
                .positiveText(R.string.dialog_positive_again)
                .autoDismiss(false)
                .positiveColorRes(R.color.back_ground_green)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {

                        mPresenter.logoutSuccess();
                    }
                })
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        if (mPresenter.checkIsAnyCriminalEscape())
                        {
                            AppUtil.showShortToast(context, "当前有设备为非正常状态或距离超过"+SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)+"米，不允许结束任务！");
                        }
                        else{
                            paramAnonymousMaterialDialog.dismiss();
                            mPresenter.logoutAllFootRing();
                        }
                    }
                })
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     *sim错误结束任务
     */
//    protected void simInitError(final String missID) {
//        ViewUtil.removeAllKeyListener(new MaterialDialog.Builder(this)
//                .title(R.string.dialog_title_problem)
//                .content("脚环:" + missID + " 获取Sim卡信息失败\n\n请注销重新检查！")
//                .positiveText(R.string.dialog_positive_sleep)
//                .canceledOnTouchOutside(false)
//                .positiveColorRes(R.color.back_ground_green)
//                .onPositive(new MaterialDialog.SingleButtonCallback() {
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction dialogAction) {
//                        mPresenter.logoutFootRing(missID);
//                    }
//                }).build());
//    }

    /**
     *sim错误请求结束任务
     */
    protected void simInitErrorMissOpen(String missID) {
        ViewUtil.removeAllKeyListener(new MaterialDialog.Builder(getContext())
                .title(R.string.dialog_title_problem)
                .content("脚环:" + missID + " 获取Sim卡信息失败\n\n请结束任务重新检查！")
                .positiveText(R.string.close_upload_data)
                .canceledOnTouchOutside(false)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction dialogAction) {
                        mPresenter.requestStopMiss();
                    }
                }).build());
    }

    /**
     * 结束任务后才可以退出
     */
    @Override
    public void finish() {
        if (!isForceFinish&&mPresenter != null && !mPresenter.stopExit()){
            return;
        }
        super.finish();
        onStop();
        overridePendingTransition(R.anim.anim_no, R.anim.push_right_out);
    }

    @Override
    protected void onDestroy() {
        if (mServiceConnection != null){
            unbindService(mServiceConnection);
            mServiceConnection=null;
        }
        if(mConnection!=null)
        {
            unbindService(mConnection);
            mConnection=null;
        }

        AppCache.destroySignalRService();
        stopService(new Intent(this,SignalRService.class));


        Service aa=AppCache.getSignalRService();
        super.onDestroy();
    }

    /**
     * 定位服务
     */
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LocateService.LocateBinder binder = (LocateService.LocateBinder) service;
            mLocateService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mLocateService = null;
        }
    };



    @Override
    protected void onPause() {
//        if (!mNeedGrantedPermission) {
//            unbindService(conn);
//        }

        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();


    }








    /*
     * android6.0权限，onRequestPermissionsResult回调
     * */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
//        switch (requestCode) {
//            case REQUEST_CAMERA_PERMISSION: {
//                if (grantResults.length > 1
//                        && grantResults[0] == PackageManager.PERMISSION_GRANTED
//                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
//                    mNeedGrantedPermission = false;
//                    //goonWithPermissionGranted();
//                } else {
//                    finish();
//                }
//
//                break;
//            }
//        }
    }





    /* ========================= 点击事件 ========================= */

    /**
     * Take care of popping the fragment back stack or finishing the activity
     * as appropriate.
     */
    @Override
    public void onBackPressed() {

        //与上次点击返回键时刻作差
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            //大于2000ms则认为是误操作，使用Toast进行提示
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            //并记录下本次点击“返回键”的时刻，以便下次进行判断
            mExitTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
    }















    final Context context=this;


    /*
     * 关于我们
     * */
    public void onAbout(View view) {
//        Intent intent = new Intent(this, AboutActivity.class);
//        startActivityForResult(intent, 0);
//        overridePendingTransition(R.anim.slide_right_in,R.anim.slide_left_out);
    }

    /*
     * 设置
     * */
    public void onSetting(View view) {
//        Intent intent = new Intent(this, SettingActivity.class);
//        startActivityForResult(intent, 0);
//        overridePendingTransition(R.anim.slide_right_in,R.anim.slide_left_out);
    }


}
